package com.myspace.test1;

import org.kie.api.KieServices;
import org.kie.api.command.Command;
import org.kie.api.command.KieCommands;
import org.kie.server.api.marshalling.MarshallingFormat;
import org.kie.server.client.KieServicesClient;
import org.kie.server.client.KieServicesConfiguration;
import org.kie.server.client.KieServicesFactory;
import org.kie.server.client.RuleServicesClient;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.kie.api.runtime.ExecutionResults;
import org.kie.server.api.model.ServiceResponse;

/**
 * Hello world!
 */
public class App {
  
  public static final String SERVER_URL = "http://172.16.29.110:8180/kie-server/services/rest/server";
  public static final String PASSWORD = "kieserver1!";
  public static final String USERNAME = "kieserver";
  public static final String KIE_CONTAINER_ID = "test1_1.0.0-SNAPSHOT";
  public static final String KIE_SESSION_ID = "test1";
  
  public static void main(String[] args) throws IOException {
    
    // KisService 配置信息设置
    KieServicesConfiguration kieServicesConfiguration =
        KieServicesFactory.newRestConfiguration(SERVER_URL, USERNAME, PASSWORD, 10000L);
    kieServicesConfiguration.setMarshallingFormat(MarshallingFormat.JSON);
    
    // 创建规则服务客户端
    KieServicesClient kieServicesClient = KieServicesFactory.newKieServicesClient(kieServicesConfiguration);
    RuleServicesClient ruleServicesClient = kieServicesClient.getServicesClient(RuleServicesClient.class);
    // 规则输入条件
    mytestmodel mytest = new mytestmodel();
    mytest.setSex(0);
    // 命令定义，包含插入数据，执行规则
    KieCommands kieCommands = KieServices.Factory.get().getCommands();
    List<Command<?>> commands = new LinkedList<>();
    commands.add(kieCommands.newInsert(mytest, "mytestmodel"));
    commands.add(kieCommands.newFireAllRules());
    ServiceResponse<ExecutionResults> results = ruleServicesClient.executeCommandsWithResults(KIE_CONTAINER_ID,
        kieCommands.newBatchExecution(commands, KIE_SESSION_ID));
    
    // 返回值读取
    mytestmodel value = (mytestmodel) results.getResult().getValue("mytestmodel");
    System.out.println(value.toString());
  }
}
